<template>
    <div>
        <div style="display: flex;padding-bottom: 20px">
            <div style="flex :70%;">
                <el-input style="width: 200px;" placeholder="查询用户名" v-model="username"></el-input>
                <el-input style="width: 200px; margin: 0 10px 0px 10px;" v-model="name" placeholder="查询姓名"></el-input>
                <el-button type="warning" @click="load(1)">查询</el-button>
                <el-button type="info" @click="reset">重置</el-button>
            </div>
            <div style="flex :30%;">
                <el-button type="warning" plain @click="handleAdd">新增</el-button>
                <el-button type="danger" plain @click="delBatch">批量删除</el-button>
                <el-button type="success" plain @click="exportData">批量导出</el-button>
                <el-upload :action="$baseUrl+'/user/import'" :headers="{token:user.token}":on-success="handleImport" :show-file-list="false" style="display: inline-block;margin-left: 10px">
                    <el-button type="primary" plain>批量导入</el-button>
                </el-upload>
            </div>
        </div>


        <el-table  :data="tableData" :header-cell-style="{background:'aliceblue',color:'#666' ,fontSize:'16px' } "  @selection-change="handleSelectionChange">>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column label="序号" width="70px" prop="id" align="center"></el-table-column>
            <el-table-column label="用户名" prop="username" align="center"></el-table-column>
            <el-table-column label="姓名" prop="name" align="center"></el-table-column>
            <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
            <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
            <el-table-column label="地址" prop="address" align="center"></el-table-column>
            <el-table-column label="头像" align="center">
                <template v-slot="scope">
                    <el-image style="width: 50px;height: 50px;border-radius:50%" v-if="scope.row.avatar"
                              :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="角色" prop="role" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="180px">
                <template v-slot="scope">
                    <el-button type="primary" plain size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" plain size="mini" @click="del(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="margin: 10px 0">
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-size="pageSize"
                    layout="total, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog title="新增用户" :visible.sync="userFormVisble" width="30%" @close="closeDialog">
            <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">


                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="电话"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="邮箱"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input type="textarea" v-model="form.address" placeholder="地址"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-radio-group v-model="form.role">
                        <el-radio label="用户"></el-radio>
                        <el-radio label="管理员"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像" prop="avatar" style="height: 50px;align-items: flex-end">
                    <div style="display:flex;width: 200px;display: flex;justify-content: center;align-items: center">
                        <div style="flex: 1;margin-bottom: 30px">

                            <el-upload
                                    ref="upload"
                                    class="avatar-uploader"
                                    :action="$baseUrl+'/file/upload'"
                                    :headers="{ token: user.token }"
                                    :show-file-list="false"
                                    list-type="picture"
                                    :on-success="handleAvatarSuccess"
                            >
                                <el-button type="primary">上传头像</el-button>
                            </el-upload>
                        </div>
                        <div style="flex: 1;margin-bottom: 0px">
                            <img :src="form.avatar ||'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                                 style=" width: 50px;height:50px;border-radius: 50%">
                        </div>
                    </div>


                </el-form-item>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="userFormVisble = false,handleCancel()">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
    export default {
        name: "User",
        data(){
            return {
                tableData: [],//所有的数据
                pageNum: 1, //当前页码
                pageSize: 5, //每页显示的个数
                username: '',
                name: '',
                total: 0,
                userFormVisble: false,
                form: {},
                user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
                rules: {
                    username: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                    ],
                    role: [
                        {required: true, message: '请选择角色', trigger: 'blur'},
                    ],
                    avatar: [
                        {required: true, message: '请选择角色', trigger: 'blur'},
                    ],
                },
                ids:[],
                editor:null
            }
        },

        created() {
            this.load()
        },
        methods: {
            closeDialog(){
                // 销毁编辑器
                this.editor.destroy()
                this.editor = null
            },
            handleImport(res, file, fileList) {
                if (res.code === '200') {
                    this.$message.success("操作成功")
                    this.load(1)
                } else {
                    this.$message.error(res.msg)
                }
            },
            exportData(){
                if (!this.ids.length) {
                    window.open(this.$baseUrl+'/user/export?token=' + this.user.token + "&username="
                        + this.username + "&name=" + this.name)
                } else {      // [1,2,3] => '1,2,3'
                    let idStr = this.ids.join(',')
                    window.open(this.$baseUrl+'/user/export?token=' + this.user.token + '&ids=' + idStr)
                }
            },
            delBatch(){
                if (!this.ids.length){
                    this.$message.warning('请选择数据')
                    return
                }
                this.$confirm('你确认批量删除这些数据吗？','确认删除',{type:"warning"}).then(resp=>{
                    this.$request.delete('/user/delete/batch',{
                        data:this.ids
                    }).then(res=>{
                        if (res.code === '200') {
                            this.$message.success('操作成功')
                            this.load()
                        }else {
                            this.$message.error('删除失败，无法删除管理员')//弹出错误信息
                            this.load()
                        }
                    })

                }).catch(()=>{})
            },
            handleSelectionChange(rows) {
                this.ids =  rows.map(v=>v.id) //获取每一个数据的id，把一个对象数组变成一个数字数组


            },
            del(id){
                this.$confirm('你确认删除吗？','确认删除',{type:"warning"}).then(resp=>{
                    this.$request.delete('/user/delete/'+id).then(res=>{
                        if (res.code === '200') {
                            this.$message.success('操作成功')
                            this.load()
                        }else {
                            this.$message.error('删除失败，无权限')//弹出错误信息
                            this.load()
                        }
                    })

                }).catch(()=>{})
            },
            handleCancel() {
                formRef.value.resetFields();
            },
            handleEdit(row) {//编辑数据
                this.form = JSON.parse(JSON.stringify(row)) //给form对象赋值，注意要深拷贝
                this.userFormVisble = true  //打开弹窗
            },
            handleAdd() {//新增数据
                this.form = {role: '用户'}//新增数据的时候清空
                this.userFormVisble = true; //打开弹窗
            },
            save() {
                this.$refs.formRef.validate((valid) => {
                    if (valid) {
                        this.$request({
                            url: this.form.id ? '/user/update' : '/user/add',
                            method: this.form.id ? 'PUT' : 'POST',
                            data: this.form
                        }).then(res => {
                            if (res.code === '200') {//表示成功保存
                                this.$message.success('保存成功')
                                this.userFormVisble = false;
                                this.load(1)

                            } else {
                                this.$message.error(res.msg)//弹出错误信息
                            }
                        })
                    }
                })

            },
            handleAvatarSuccess(response, file, fileList) {
                // 把user的头像属性换成上传的图片的链接
                this.form.avatar = response.data
            },
            reset() {
                this.username = '',
                    this.name = '',
                    this.load();
            },
            load(pageNum) {//分页查询
                if (pageNum) this.pageNum = pageNum;

                this.$request.get('/user/selectByPage', {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        username: this.username,
                        name: this.name
                    }
                }).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total
                    console.log(res.avatar)
                })
            },
            handleCurrentChange(pageNum) {
                this.load(pageNum);
            }

        }
    }
</script>

<style scoped>


</style>